<template>
  <div class="app-container">
    <el-row :gutter="20">
      <div class="filter-container">
        <el-col style="text-align:right;margin-top: -8px;margin-bottom:10px" >
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            @click="handleHookUp"
          >
            模板设计
          </el-button>
          <el-button
            size="small"
            font-size="14px"
            class="filter-item"
            style="width:150px;margin-left: 10px;"
            type="primary"
            :loading="startLoading"
            @click="startWorkFlow"
          >
            开启十三月工资填报
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            :loading="revokeLoading"
            @click="revokeWorkFlow"
          >
            撤销启动
          </el-button>
        </el-col>
      </div>
    </el-row>
    <div class="grid-content bg-purple" />
    <div
      ref="box"
      class="box"
    >

      <div
        class="mid"
        :class="[isActive ? 'mids': 'min']"
      >
        <!-- 表格部分 -->
        <el-table
          ref="singalTable"
          v-loading="listLoading"
          :data="list"
          :stripe="true"
          :height="tableHeight"
          fit
          style="width: 100%;  margin-left:10px"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        >
          <template slot="empty">
            <tableEmpty />
          </template>
          <el-table-column type="index" align="center" width="50" label="序号" />
          <el-table-column label="工资类型" prop="merit_pay_code" align="center" >
          <template slot-scope="{row}">
              <span style="float: center">{{ row.merit_pay_code | meritPayCodeFilter(that)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="工资项" prop="salary_codes" align="center" >
            <template slot-scope="{row}">
              <span style="float:left">{{ row.salary_codes | salaryNameFilter(that) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="发放比例"  prop="percent"  align="center">
            <template slot-scope="{row}">
              <span style="float: center">{{row.percent | percentfilter(that)}}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
    </div>
    <Drag ref="icon" />
    <!--模板设计 -->
    <el-dialog  v-dialogDrag   title="模板设计" :visible.sync="hookUpFormVisible" width="90%" :close-on-click-modal="false">
      <el-form ref="hookUpForm" :model="formData" label-position="right" label-width="120px" size="small">
        <el-row class="el-row-out">
          <el-col :span="6">
            <el-row>
              <el-tree
                ref="treee"
                node-key="id"
                :highlight-current="true"
                :accordion="true"
                show-checkbox
                :data="agencyTreeData"
                :props="defaultPropss"
                class="el-tree-out"
                style="height: 999px; margin-right: 10px"
                :default-expanded-keys="['0']"
              />
            </el-row>
          </el-col>
          <el-col :span="18">
            <!-- <el-row>
              <el-col>
                <span style="font-weight: 600">模板设计：</span>
              </el-col>
            </el-row> -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="模板月份:">
                <el-select v-model="formData.month" class="filter-item" placeholder="--请选择--" style="width:100%" >
                    <el-option label="一月" value="01" />
                    <el-option label="二月" value="02" />
                    <el-option label="三月" value="03" />
                    <el-option label="四月" value="04" />
                    <el-option label="五月" value="05" />
                    <el-option label="六月" value="06" />
                    <el-option label="七月" value="07" />
                    <el-option label="八月" value="08" />
                    <el-option label="九月" value="09" />
                    <el-option label="十月" value="10" />
                    <el-option label="十一月" value="11" />
                    <el-option label="十二月" value="12" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="border: 1px solid #f2f2f2; margin-top: 1%" class="thirteenMould"  v-for="project in personTypeSalaryList" :key="project.meritPayCode">
              <el-col :span="6">
                <el-form-item label="工资项类别" style="background-color: #f2f2f2" />
                <el-input disabled :value="project.meritPayName"/>
              </el-col>
              <el-col :span="15">
                <el-form-item label="工资项名称" style="background-color: #f2f2f2" />
                <el-checkbox-group 
                  v-model="project.columnNames"
                >
                 <el-col v-for="item in project.salaryCodes" :key="item.salaryCode" :span="4">
                  <el-checkbox  
                    :label="item.salaryCode" 
                    :key="item.salaryCode" 
                    :disabled="item.salaryCode == 's1'" 
                    :title="item.salaryName" 
                  >
                    {{item.salaryName}}
                  </el-checkbox>
                 </el-col>
              </el-checkbox-group>
              </el-col>
              <el-col :span="3">
                <el-form-item label="发放倍数" title='发放比例' style="background-color: #f2f2f2" />
                <el-input-number class="project-percent"  v-model="project.percent" :precision="2" :min="0" :max="99" :controls="false"/>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row>
          <el-col style="text-align: center; margin-top:2%">
            <el-button type="primary" :loading="saveLoading" @click="handleSaveHookUpData">
              确定
            </el-button>
            <el-button @click="hookUpFormVisible = false">
              取消
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { querySalaryNameDict} from "@/api/unitSalaryReport/unitSalaryReport"
import { getAllPersonTypeSalary,queryThirteenSalaryMouldPage,saveThirteenSalaryMould,
queryThirteenSalaryAgencyIds,updateThirteenSalaryMould,startDoWorkFlow,revokeThirteenMould } from '@/api/thirteen/thirteen'
import { getAuthAgencyTree} from '@/api/baseInfo'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import AgencyTree from '@/components/tree/agencyTree'
import Drag from '@/components/Drag'
export default {
  name: 'thirteenMould',
  components: { Pagination, tableEmpty, AgencyTree, Drag },
  filters: {
    meritPayCodeFilter(type, that){
  // 工资类别
        const meritPayCodeList = that.meritPayCodeList
        for (const item in meritPayCodeList) {
          if (meritPayCodeList[item].code === type) {
            return meritPayCodeList[item].name
          }
        }
    },// 工资项滤器
    salaryNameFilter(value, that) {
      const revalue=[]
      const salaryNames = that.salaryNames;
      value.split(',').forEach(s =>{
        for (const item of salaryNames) {
        if (item.value === s && item.isShow === 1) {
          revalue.push(item.key)
        }
      }
      })
      return revalue.join(',')
    },
    percentfilter(value, that){
      if(value){
        return value*100+'%'
      }
    }
  },
  data() {
    return {
      that:this,
      defaultPropss: {
        children: 'children',
        label: 'label'
      },
      meritPayCodeList:this.$store.getters.meritPayCodeList,//工资类型
      salaryNames: [],
      agencyTreeData: [], // 树数据集合
      treeHeight: null,
      isActive: true,
      Show: false,
      treeShow: false,
      treeData: '',
      tableHeight: null,
      list: [],
      personTypeSalaryList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 200,
        year: ''
      },
      isWorkflowStart: '',
      hookUpFormVisible: false,
      formData: {
        agencyIds: [],
        thirteenAgencyVerify: [],
        moulds:[],
        month:'',
        mouldKey:'',
        menuid: this.$router.currentRoute.meta.menuid
      },
      saveLoading: false,
      startLoading: false,
      revokeLoading: false,
      salaryData: []
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    }
  },
  created() {
    this.initBaseInfo()
    this.getList()
  },
  mounted() {
    this.getTbHeight()
    this.dragController()
    this.getTreeData()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },

  methods: {
    getTreeData() {
      getAuthAgencyTree().then(response => {
        this.agencyTreeData = response.data
      })
    },
    // 拖拽
    dragController() {
      this.$refs.icon.dragControllerDiv()
    },
  
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 228
      this.treeHeight = window.innerHeight - 228
    },
    getList() {
      this.listLoading = true
      queryThirteenSalaryMouldPage(this.listQuery).then(response => {
        this.list = response.data.rows 
        this.total = response.data.total
        if(this.total !== 0){
         this.formData.month=this.list[0].mould_month
         this.formData.mouldKey=this.list[0].biz_key
         this.isWorkflowStart=this.list[0].is_workflow_start
        }
        this.listLoading = false
      })
    },
    handleQuery() {
      this.listQuery.page = 1
    },
    // 编辑模板
    handleHookUp() {
      if(this.isWorkflowStart == 1){
        this.$message({
          showClose: true,
          message: '流程已启动！无法编辑模板！',
          type: 'warning',
          duration: 2000
        })
        return
      }
      if(this.total !== 0){
         this.list.forEach(dataitem =>{
          this.personTypeSalaryList.forEach(item =>{
           if(dataitem.merit_pay_code==item.meritPayCode){
             item.columnNames=dataitem.salary_codes.split(',').filter(function (value,index) {
              return value.indexOf('s')!=-1
              })
             item.percent=dataitem.percent
           }
          })
         })
       }
      this.formData.agencyIds.forEach((index,node)=>{
          this.$nextTick(()=>{
            this.$refs.treee.setChecked(index,true)
          });
      })
      this.hookUpFormVisible = true
    },

    // 保存
    handleSaveHookUpData() {
      this.saveLoading=true
      if(this.formData.month === ''){
         this.$message({
          showClose: true,
          message: '请选择模板月份！',
          type: 'warning',
          duration: 2000
        })
        this.saveLoading=false
        return
      }
      
      this.formData.agencyIds = []
      if (this.$refs.treee.getCheckedNodes().filter(item => { return !item.children }) &&
          this.$refs.treee.getCheckedNodes().filter(item => { return !item.children }).length > 0) {
        this.$refs.treee.getCheckedNodes().filter(item => { return !item.children }).forEach(s => {
          this.formData.agencyIds.push(s.id)
        })
      }
      if(!this.formData.agencyIds.length>0){
        this.$message({
          showClose: true,
          message: '请选择单位！',
          type: 'warning',
          duration: 2000
        })
        this.saveLoading=false
          return
      }
      const moulds=new Array()
      this.personTypeSalaryList.forEach(s => {
        if(s.percent == '' || s.percent == null){
          s.percent=1
        }
        const mouldForm= {'meritPayCode':s.meritPayCode,
        'salaryCodes':s.columnNames.join(','),
        'month':this.formData.month,
        'percent':s.percent,
        'mouldKey':this.formData.mouldKey
        }
        moulds.push(mouldForm)
      })
      this.formData.moulds=moulds
      if(this.formData.mouldKey === ''){
        saveThirteenSalaryMould(this.formData).then(response => {
          this.$message({
          showClose: true,
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
          this.saveLoading=false
          this.hookUpFormVisible=false
          this.getList()
          this.initBaseInfo()
        }).catch(err =>{
          this.saveLoading=false
        })
      }else{
        updateThirteenSalaryMould(this.formData).then(response => {
          this.$message({
          showClose: true,
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
          this.saveLoading=false
          this.hookUpFormVisible=false
          this.getList()
          this.initBaseInfo()
        }).catch(err =>{
          this.saveLoading=false
        })
      }
    },
    // 启动十三月流程
    startWorkFlow(){
      this.startLoading=true
      if(this.isWorkflowStart == 1){
        this.$message({
          showClose: true,
          message: '流程已启动！请勿重复启动！',
          type: 'warning',
          duration: 2000
        })
        this.startLoading=false
        return
      }
      startDoWorkFlow(this.formData).then(response => {

        if(response.rscode==100000){
          this.startLoading=false
          this.$message({
          showClose: true,
          message: '流程启动成功！',
          type: 'success',
          duration: 2000
        })
          this.getList()
          this.initBaseInfo()
        }
      }).catch(err =>{
        this.startLoading=false
      })
    },
    revokeWorkFlow(){
      this.revokeLoading=true
      if(this.isWorkflowStart == 0){
        this.$message({
          showClose: true,
          message: '流程未启动！无需撤销！',
          type: 'warning',
          duration: 2000
        })
        this.revokeLoading=false
        return
      }
      revokeThirteenMould().then(response => {
        if(response.rscode==100000){
          this.revokeLoading=false
          this.$message({
          showClose: true,
          message: '撤销启动成功！数据已收回！',
          type: 'success',
          duration: 2000
        })
          this.getList()
          this.initBaseInfo()
        }}).catch(err =>{
        this.revokeLoading=false
      })
    },

    // 树点击
    handleNodeClick(data) {
      if (data.isleaf === '1') {
        this.formData.depBgtEcoCode = data.code
        this.depBgtEcoName = data.label
        this.$refs.selectReport.blur()
      }
    },
    // 初始化基础数据
    initBaseInfo() {
      queryThirteenSalaryAgencyIds(this.listQuery).then((response) => {
        this.formData.thirteenAgencyVerify=response.data
        this.formData.thirteenAgencyVerify.forEach(s => {
          this.formData.agencyIds.push(s.agencyId)
        })
      })
      //获取工资类型工资项配置
      getAllPersonTypeSalary().then((response) => {
        this.personTypeSalaryList = response.data
      })
      // 查询工资项名称
      querySalaryNameDict().then((res) => {
          this.salaryNames = res.data;
        })
        .catch(() => {
          this.salaryNames = [];
        });
    }
  }
}
</script>
<style lang="scss" scoped>
  
 .el-form-item__label {
        text-align: justify;
    }
  .dialogFlex{
    display: flex;
  }
  .cell-input{
    width: 80%;
  }
  ::v-deep .indexTable {
    .el-table__header-wrapper {
      .el-checkbox {
        display: none;
      }
    }

  }
  ::v-deep.hookUpTable {
    .el-input{
      width: auto !important;
    }
  }
  ::v-deep.el-select-dropdown__item.selected {
    font-weight: normal;
  }
  .el-row-out {
    display: flex;
    flex-wrap: wrap;
    .el-tree-out {
      height: auto;
      max-height: 500px;
      overflow: auto;
    }
    .tipsCol {
      margin-top: 5%;
    }

    .tipsSpan {
      color: #ff0000;
      font-size: 18px;
      font-weight: 600;
    }
  }
</style>
<style>
  label > span.el-checkbox__label{
    width: 80px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: inline-block;
    padding-left: 10px;
    line-height: 19px;
    font-size: 14px;
  }
.project-percent input{
    width: 60% ;
  }
</style>
